<template>
  <!-- 人员管理--新增和编辑 -->
  <el-dialog :title="mode=='add'?'新增':'编辑'"
             class="addPersonage"
             width='662px'
             :close-on-click-modal="false"
             :visible.sync="visible">
    <!-- 具体表单 -->
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()"
             label-width="100px">
      <el-form-item label="姓名"
                    prop="userName">
        <el-input v-model="dataForm.userName"
                  placeholder="姓名"></el-input>
      </el-form-item>

      <el-form-item label="性别"
                    prop="sex">
        <!-- <el-input v-model="dataForm.sex"
                  placeholder="性别"></el-input> -->
        <el-select v-model="dataForm.sex"
                   placeholder="请选择">
          <el-option v-for="item in options"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄"
                    prop="age">
        <el-input v-model="dataForm.age"
                  placeholder="年龄"></el-input>
      </el-form-item>
      <el-form-item label="电话"
                    prop="phone">
        <el-input v-model="dataForm.phone"
                  placeholder="电话"></el-input>
      </el-form-item>
      <el-form-item label="身份证号码"
                    prop="idNumber">
        <el-input v-model="dataForm.idNumber"
                  placeholder="身份证号码"></el-input>
      </el-form-item>
      <!-- <el-form-item label="地址"
                    prop="address">
        <el-input v-model="dataForm.address"
                  placeholder="地址"></el-input>
      </el-form-item> -->
      <el-form-item label="所在地区"
                    prop="address">
        <el-cascader v-model="address"
                     :options="citydata"
                     separator=' '
                     @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址"
                    prop="area">
        <el-input v-model="dataForm.area"
                  placeholder="详细地址"></el-input>
      </el-form-item>
      <el-form-item label="银行卡号"
                    prop="bakInfo.bankCardNumber">
        <el-input v-model="dataForm.bakInfo.bankCardNumber"
                  placeholder="银行卡号"></el-input>
      </el-form-item>
      <el-form-item label="开户银行"
                    prop="bakInfo.bankName">
        <el-input v-model="dataForm.bakInfo.bankName"
                  placeholder="开户银行"></el-input>
      </el-form-item>
      <el-form-item label="收款人姓名"
                    prop="bakInfo.pname">
        <el-input v-model="dataForm.bakInfo.pname"
                  placeholder="收款人姓名"></el-input>
      </el-form-item>
      <!-- <el-form-item label="银行卡号"
                    prop="bakInfo.bankCardNumber">
        <el-input v-model="dataForm.bakInfo.bankCardNumber"
                  placeholder="银行卡号"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="开户银行"
                    prop="bakInfo.bankName">
        <el-input v-model="dataForm.bakInfo.bankName"
                  placeholder="开户银行"></el-input>
      </el-form-item> -->
      <!--<el-form-item label="卡号信息"
                    prop="bakInfo.cardInfo">
        <el-input v-model="dataForm.bakInfo.cardInfo"
                  placeholder="卡号信息"></el-input>
      </el-form-item> -->
      <el-form-item label="是否实名认证"
                    prop="isAuth">
        <!-- <el-input v-model="dataForm.isAuth"
                  placeholder="是否实名认证"></el-input> -->
        <el-radio v-model="dataForm.isAuth"
                  label="0">未实名</el-radio>
        <el-radio v-model="dataForm.isAuth"
                  label="1">实名</el-radio>
      </el-form-item>
      <el-form-item label="是否禁用"
                    prop="status">
        <!-- <el-input v-model="dataForm.status"
                  placeholder="是否禁用"></el-input> -->
        <el-radio v-model="dataForm.status"
                  label="1">启用</el-radio>
        <el-radio v-model="dataForm.status"
                  label="0">禁用</el-radio>
      </el-form-item>
      <!-- 头像 -->
      <el-form-item label="头像"
                    prop="avatarUrl">
        <el-upload class="avatar-uploader"
                   :action="action"
                   name="file"
                   :headers='headers'
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.avatarUrl"
               :src="dataForm.avatarUrl"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer"
          class="dialog-footer">
      <el-button type="primary"
                 class="btn"
                 @click="addSave"
                 v-if="mode == 'add'">确认新增</el-button>
      <el-button type="primary"
                 class="btn"
                 @click="update"
                 v-else>确认修改</el-button>
    </span>
  </el-dialog>
</template>

<script>
import citydata from '@/utils/citydata.js'
export default {
  // props: ['mode'],
  data () {
    return {
      mode: 'add',
      // 隐藏
      visible: false,
      // 数据
      // menuList: [],
      // menuListTreeProps: {
      //   label: 'name',
      //   children: 'children'
      // },
      dataForm: {
        bakInfo: {
        }
      },
      // 身份证：/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
      dataRule: {
        userName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        'bakInfo.bankCardNumber': [
          { required: true, message: '银行卡号不能为空', trigger: 'blur' }
        ],
        'bakInfo.bankName': [
          { required: true, message: '开户银行不能为空', trigger: 'blur' }
        ],
        'bakInfo.pname': [
          { required: true, message: '收款人姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // 手机号正则校验
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的手机号'))
              }
            }
          }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号码', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // 身份证号码正则校验
              let _reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的身份证号码'))
              }
            }
          }
        ]
      },
      options: [{
        value: '男',
        label: '男'
      }, {
        value: '女',
        label: '女'
      }],
      citydata: citydata,
      address: [],
      provinces2: '',
      area: '',
      // 图片上传地址
      headers: {
        token: ''
      },
      action: '',
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    }
  },
  created () {
    // /sys/config/upload-img
    this.action = this.$baseUrl + '/sys/config/upload-img'
    this.headers.token = this.$cookie.get('token')
    this.address = []
  },
  // 计算属性
  // computed: {
  //   dataForm: {
  //     address: () => {
  //       return this.provinces2 + this.area
  //     }
  //   }
  // },
  methods: {
    // 父调用的方法
    addInit () {
      this.visible = true
    },
    init (id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.$http({
        url: this.$http.adornUrl('/sys/user/person/info/' + this.dataForm.id),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.dataForm = data.personUser
        try {
          this.address = this.dataForm.address.split(' ')
        } catch (error) {
          // this.dataForm.address = []
        }
        // console.log(this.dataForm.address)
        if (!data.personUser.bakInfo) {
          this.dataForm.bakInfo = {
            bankCardNumber: '',
            bankName: '',
            pname: ''
          }
        }
        this.dataForm.status = this.dataForm.status + ''
        this.dataForm.isAuth = this.dataForm.isAuth + ''
      })
    },
    // 修改
    update () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.address = this.provinces2
          this.$http({
            url: this.$http.adornUrl('/sys/user/person/update'),
            method: 'post',
            data: this.$http.adornParams(this.dataForm)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  // 成功之后的回调
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 新增
    // /sys/user/person/save
    addSave () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.bakInfo.isShow = 1
          try {
            this.dataForm.address = this.provinces2
          } catch (error) {
          }
          this.$http({
            url: this.$http.adornUrl('/sys/user/person/save'),
            method: 'post',
            data: this.$http.adornParams(this.dataForm)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  // 成功之后的回调
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 图片上传成功处理
    handleAvatarSuccess (res, file) {
      this.dataForm.avatarUrl = 'http://' + res.url
      // this.dataForm.companyLicense = URL.createObjectURL(file.raw)
      // this.dataForm.companyLicense = uploadImgToBase64(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = (file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif')
      const isLt2M = file.size / 1024 / 1024 < 0.2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG，png，gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 200k!')
      }
      return isJPG && isLt2M
    },
    handleChange (value) {
      // console.log(this.provinces)
      if (value.length > 2) {
        this.provinces2 = value[0] + ' ' + value[1] + ' ' + value[2]
      } else {
        this.provinces2 = value[0] + ' ' + value[1]
      }
      // console.log(value)
      // console.log(this.provinces2)
    }
    // 结束
  }
}
</script>

<style lang="scss">
.addPersonage {
  .el-input.el-input--medium {
    width: 370px;
  }
  .el-dialog__header {
    background-color: #f8f8f8;
  }
  .el-dialog__body {
    display: flex;
    justify-content: center;
  }
  .btn {
    width: 370px;
  }
  .dialog-footer {
    text-align: center !important;
    padding-bottom: 39px;
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 39px;
  }
  // 上传
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    // border-radius: 6px;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
</style>
